package com.lhq.business.service.impl;

import com.lhq.business.domain.Book;
import com.lhq.business.service.IBookService;
import com.lhq.business.service.IRankingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author lhq
 * @version 1.0
 * @date 2024/7/29 9:16
 */
@Service
public class RankingServiceImpl implements IRankingService {
    @Autowired
    private RedisTemplate  redisTemplate;
    @Autowired
    private IBookService bookService;
    @Override
    public List<Book>  getTopRankingList(String rankingType, int size) {
        Set<String> range = redisTemplate.opsForZSet().reverseRangeByScore(rankingType, 0,Double.MAX_VALUE);
        // Set<String> range = redisTemplate.opsForZSet().range(rankingType, 0, size);
        List<Book> ranking = range.stream().map(bookId ->
            bookService.selectById(bookId)
            ).collect(Collectors.toList());
        return ranking;
    }
    /**
     *  添加书籍到排行榜
     * @author lhq
     * @date 2024/7/29 9:43
     * @version 1.0
     */
    @Override
    public Boolean addBook(String rankingType, String bookId, double score) {
        return redisTemplate.opsForZSet().add(rankingType, bookId ,score);
    }
    /**
     *  添加书籍分数(在原来基础上加分数)
     * @author lhq
     * @date 2024/7/29 9:43
     * @version 1.0
     */
    @Override
    public Double incrementScore(String rankingType, String bookId, double addScore) {
        return redisTemplate.opsForZSet().incrementScore(rankingType, bookId ,addScore);
    }


    /**
     * 获取排行榜上的成员
     *
     * @param rankingType
     * @param start
     * @param end
     * @return: java.util.Set<java.lang.String>
     * @author lhq
     * @date: 2024/7/29 9:44
     */
    public Set<String> getBookIds(String rankingType, int start, int end) {
        return redisTemplate.opsForZSet().range(rankingType, start, end);
    }

    /**
     * 获取成员的排名
     *
     * @param rankingType
     * @param BookId
     * @return: java.lang.Long
     * @author lhq
     * @date: 2024/7/29 9:44
     */
    public Long getBookRank(String rankingType, String BookId) {
        return redisTemplate.opsForZSet().rank(rankingType, BookId);
    }

    /**
     * 获取成员的分数
     *
     * @return:
     * @author lhq
     * @date: 2024/7/29 9:44
     */
    public Double getBookScore(String rankingType, String BookId) {
        return redisTemplate.opsForZSet().score(rankingType, BookId);
    }

    /**
     * 删除成员
     * @param rankingType
     * @param BookId
     * @return: java.lang.Long
     * @author lhq
     * @date: 2024/7/29 9:45
     */
    public Long removeBook(String rankingType, String BookId) {
        return redisTemplate.opsForZSet().remove(rankingType, BookId);
    }
}
